package com.five.service.impl;

import com.five.api.CommentServiceAPI;
import com.five.api.NovelApi;
import com.five.api.NovelServiceApi;
import com.five.api.ReaderServiceAPI;
import com.five.dto.IdRequest;
import com.five.dto.ReplyRequest;
import com.five.mapper.InteractionMapper;
import com.five.pojo.Comment;
import com.five.pojo.Interaction;
import com.five.pojo.Novel;
import com.five.result.Result;
import com.five.service.AuthorInteractionService;
import com.five.vo.CommentTreeVO;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class AuthorInteractionServiceImpl implements AuthorInteractionService {

    @Autowired
    private InteractionMapper interactionMapper;
    @Autowired
    private NovelApi novelServiceAPI;
    @Autowired
    private ReaderServiceAPI readerServiceAPI;
    @Autowired
    private CommentServiceAPI commentServiceAPI;

    @Override
    public List<Novel> getAuthorBooksWithComments(Long authorId) {
        try {
            log.info("开始查询作者 {} 的书籍及评论", authorId);

            // 1. 查询作者所有书籍
//            List<Novel> authorNovels = novelMapper.selectByAuthorId(authorId);
            // 使用 FeignClient
            IdRequest idRequest = new IdRequest();
            idRequest.setAuthorId(authorId);
            Result<List<Novel>> authorBooks = novelServiceAPI.getAuthorBooks(idRequest);
            List<Novel> authorNovels = authorBooks.getData();


            log.info("查询到作者 {} 的书籍数量: {}", authorId, authorNovels.size());

            // 2. 为每本书查询评论及回复
            for (Novel novel : authorNovels) {

                // 使用 FeignClient调用接口
                IdRequest idRequest1 = new IdRequest();
                idRequest1.setNovelId(novel.getId());
                Result<List<CommentTreeVO>> commentTree = commentServiceAPI.getCommentTree(idRequest1);

                System.out.println(commentTree);
                List<CommentTreeVO> data = commentTree.getData();
                System.out.println(data);
//                idRequest1.setNovelId(novel.getId());
//                List<Comment> comments = readerServiceAPI.getBooksWithComments(idRequest1).getData();


//                // 处理可能的 null 值
//                if (comments == null) {
//                    comments = new ArrayList<>();
//                    log.warn("书籍 {} 的评论查询返回了null，已初始化为空列表", novel.getId());
//                }
//
//                log.info("书籍 {} 的评论数量: {}", novel.getId(), comments.size());
//
//                // 3. 为每条评论查询作者回复
//                for (Comment comment : comments) {
//                    // 确保 comment 不为 null
//                    if (comment != null) {
//                        List<Interaction> replies = interactionMapper.selectRepliesByCommentId(comment.getId());
//
//                        // 处理可能的 null 值
//                        if (replies == null) {
//                            replies = new ArrayList<>();
//                        }
//
//                        comment.setAuthorReplies(replies);
//                    }
//                }

                novel.setComments(data);
            }

            return authorNovels;

        } catch (Exception e) {
            log.error("获取作者 {} 的书籍评论失败", authorId, e);
            throw new RuntimeException("获取书籍评论失败: " + e.getMessage(), e);
        }
    }

    @Override
    @Transactional//本地事务注解
    @GlobalTransactional//添加全局事务注解
    public void replyToComment(ReplyRequest request) {
        // 封装作者回复
        Interaction interaction = new Interaction();
        interaction.setAuthorId(request.getAuthorId());
        interaction.setReaderId(request.getReaderId());
        interaction.setCommentId(request.getCommentId());
        interaction.setContent(request.getContent());
        interaction.setCreateTime(LocalDateTime.now());
        interaction.setUpdateTime(LocalDateTime.now());

        int result = interactionMapper.insert(interaction);
        if (result > 0) {
            // 更新评论的回复数量
//            commentMapper.incrementReplyCount(request.getCommentId());
            // 使用 FeignClient调用接口
            IdRequest idRequest = new IdRequest();
            idRequest.setCommentId(request.getCommentId());
            readerServiceAPI.updateReplyCount(idRequest);
        }
    }


    /**
     * 删除作者回复
     *
     * @param interactionId
     */
    @Override
    public void deleteInteraction(Long interactionId) {
        interactionMapper.deleteInteraction(interactionId);
        log.info("删除作者回复成功");
    }

}
